package com.duobao.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.duobao.entity.pojo.UserInfo;
import com.duobao.entity.vo.Result;
import com.duobao.entity.vo.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * 登录拦截器
 */
@Component
@Slf4j
public class LoginAuthInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求方式
        //如果请求方式是options 预检请求 ， 直接放行
        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {
            return true;
        }

        //从请求头获取token
        String token = request.getHeader("token");

        //如果token为空，返回错误提示
        if (StrUtil.isEmpty(token)) {
            responseNoLoginInfo(response);
            return false;
        }

        //如果token不为空，拿着token查询redis
        String userInfoJSON = redisTemplate.opsForValue().get("userInfo:" + token);
        log.info("token,{}", userInfoJSON);
        //如果redis如果查询不到信息，返回错误提示
        if (StrUtil.isEmpty(userInfoJSON)) {
            responseNoLoginInfo(response);
            System.out.println("失败");
            return false;
        }
        //如果redis查询到用户信息，把用户信息放到ThreadLocal里面
        AuthContextUtil.setUserInfo(JSON.parseObject(userInfoJSON, UserInfo.class));
        // 更新用户信息数据时间
        redisTemplate.expire("userInfo:" + token, 7, TimeUnit.DAYS);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        //threadLocal 删除
        AuthContextUtil.removeUserInfo();
    }

    //响应状态码给前端
    private void responseNoLoginInfo(HttpServletResponse response) {
        Result<Object> result = Result.error("用户未登录", ResultCodeEnum.LOGIN_AUTH);
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) writer.close();
        }
    }
}
